package com.acraftsman.mr_camera;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.acraftsman.mr_camera.utils.LocalScanUtils;
import com.sosocam.ipcam.IPCam;
import com.sosocam.ipcam.IPCamVideoView;
import com.sosocam.ipcammgr.IPCamMgr;
import com.sosocam.rcipcam.DISCOVERED_CAMERA_INFO;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import io.flutter.embedding.android.FlutterActivity;

public class ClientActivity extends FlutterActivity {

    private String ipCamUser="admin";
    private String ipCamPwd="12345678";
    private boolean connectFlag;

    private ImageView iv_scan_view;//跳转
    private ImageView iv_light;//闪光灯
    private LinearLayout iv_light_layout;//闪光灯
    private TextView tv_order_index;//序号
    private TextView tv_username;//户名
    private TextView tv_userno;//户号
    private TextView tv_phone;//电话
    private TextView tv_address;//地址
    private TextView tv_start_num;//上期行度
    private ImageView iv_back;//返回键

    private LinearLayout iv_takephoto_view_layout;//拍照

    private FrameLayout mFrameLayout;
    private IPCamVideoView ipCamVideoView;//抄表杆区域

    private LocalScanUtils localScanUtils;//工具类
    private String cameraIp = null;//相机ip

    private String light = "0";//1开启闪光灯  0关闭闪光灯
    private boolean clickFlag = true;//点击拍照事件标志

    private LinkedHashMap<String, IPCam> camList;//初始化获取的广播摄像头
    private IPCam ipCam;
    private SharedPreferences preference;
    private String snapshot_file_path;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    cameraIp = ipCam.ip();
                    if(!ipCamVideoView.state().equals("PLAYING")){
                        ipCam.play_video(0);
                    }
                    if (light.equals("0")) {//手电筒已打开
                        localScanUtils.showLed(cameraIp, "0");
                        iv_light.setImageResource(R.drawable.light_down);
                    } else {//已关闭
                        localScanUtils.showLed(cameraIp, "100");
                        iv_light.setImageResource(R.drawable.light_on);
                    }
                    break;
                case 1:
                    //进行预览
                    clickFlag = true;
                    if(!ipCamVideoView.state().equals("PLAYING")){
                        ipCam.play_video(0);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        setContentView(R.layout.activity_client);
        initView();
        /* 注册屏幕唤醒时的广播 */
        IntentFilter mScreenOffFilter = new IntentFilter("android.intent.action.SCREEN_OFF");
        ClientActivity.this.registerReceiver(mScreenOffReceiver, mScreenOffFilter);
    }

    public void initView() {
        preference = PreferenceManager.getDefaultSharedPreferences(this);
        localScanUtils = new LocalScanUtils();
        iv_scan_view = findViewById(R.id.iv_scan_view);
        iv_light = findViewById(R.id.iv_light);
        iv_light_layout = findViewById(R.id.iv_light_layout);
        iv_back = findViewById(R.id.iv_back);
        tv_order_index = findViewById(R.id.tv_order_index);
        tv_username = findViewById(R.id.tv_username);
        tv_userno = findViewById(R.id.tv_userno);
        tv_phone = findViewById(R.id.tv_phone);
        tv_address = findViewById(R.id.tv_address);
        tv_start_num = findViewById(R.id.tv_start_num);
        mFrameLayout = findViewById(R.id.mFrameLayout);

        iv_takephoto_view_layout = findViewById(R.id.iv_takephoto_view_layout);

        ipCamVideoView = findViewById(R.id.ipCamVideoView);

        camList = IPCamMgr.get_cameras_list();

        //点击拍照识别
        iv_takephoto_view_layout.setOnClickListener(view -> takePhoto());

        //切换抄表杆
        iv_scan_view.setOnClickListener(view -> changeCamera());

        //打开手电筒
        iv_light_layout.setOnClickListener(view -> {
            if (light.equals("1")) {//手电筒已打开
                localScanUtils.showLed(cameraIp, "0");
                light = "0";
                iv_light.setImageResource(R.drawable.light_down);
            } else {//已关闭
                localScanUtils.showLed(cameraIp, "100");
                light = "1";
                iv_light.setImageResource(R.drawable.light_on);
            }
            setSharedLightStatus();
        });

        iv_back.setOnClickListener(view -> goBack());

        mFrameLayout.setOnClickListener(v -> takePhoto());

        //获取token
        Intent intent = getIntent();
        String userDetailStr = intent.getStringExtra("userDetail");
        if(userDetailStr != null && !userDetailStr.equals("")) {
            try{
                JSONObject userDetail = new JSONObject(userDetailStr);
                tv_phone.setText(userDetail.getString("phone"));
                tv_start_num.setText(userDetail.getString("startNum"));
                tv_userno.setText(userDetail.getString("userNo"));
                tv_username.setText(userDetail.getString("username"));
                tv_order_index.setText(userDetail.getString("index"));
                tv_address.setText(userDetail.getString("address"));
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
        snapshot_file_path = intent.getStringExtra("snapshotFilePath");;

        //连接抄表杆
        ipCamVideoView.setKeepScreenOn(true);
        ipCamVideoView.setVisibility(View.VISIBLE);
        connectClient();

        light = preference.getString("lightStatus","0");
        if (light.equals("1")) {
            localScanUtils.showLed(cameraIp, "100");
            iv_light.setImageResource(R.drawable.light_on);
        } else {
            localScanUtils.showLed(cameraIp, "0");
            iv_light.setImageResource(R.drawable.light_down);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mScreenOffReceiver);
        //关闭闪光灯
        if(cameraIp != null){
            localScanUtils.showLed(cameraIp, "0");
        }
    }

    public void changeCamera() {
        invokeSendPhotoResult("changeCamera");
        finish();
    }

    public void goBack() {
        invokeSendPhotoResult("back");
        finish();
    }

    public void setSharedLightStatus(){
        SharedPreferences.Editor editor = preference.edit();
        editor.putString("lightStatus", light);
        // 提交数据
        editor.apply();
    }

    //调用方法 result（success: 成功， error: 失败）
    public void invokeSendPhotoResult(String result) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("result", result);
        setResult(Activity.RESULT_OK, resultIntent);
        finish();
    }

    public void takePhoto(){
        if(ipCam == null){
            invokeSendPhotoResult("error");
            return;
        }
        if (clickFlag) {
            clickFlag = false;
            File folder = new File(snapshot_file_path.substring(0,snapshot_file_path.lastIndexOf("/")));
            if(!folder.exists()){
                folder.mkdirs();
            }
            IPCam.ERROR ipCamError = ipCam.snapshot(snapshot_file_path,path -> {
                System.out.println("拍照路径：" + path);
            });
            localScanUtils.showKa(ClientActivity.this);
            ipCam.stop_video();
            invokeSendPhotoResult(ipCamError == IPCam.ERROR.NO_ERROR ? "success" : "error");
        } else {
            //重置信息 并重新预览
            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);
        }
    }

    //连接抄表杆
    public void connectClient(){
        //搜索局域网中的机器 先判断是否有记录的设备  存在则直接连接
        if(camList.size()==0){
            boolean connectFlag = true;
            long start = System.currentTimeMillis();
            while(connectFlag){
                long end = System.currentTimeMillis();
                camList = IPCamMgr.get_cameras_list();
                LinkedHashMap<String, DISCOVERED_CAMERA_INFO> disCamList = IPCamMgr.get_discovered_cameras_list();
                if(disCamList.size()>0){//发现摄像头
                    List<DISCOVERED_CAMERA_INFO> discoveredCameraInfoList = new ArrayList<>(disCamList.values());
                    String ipCamAlias = discoveredCameraInfoList.get(0).alias;
                    String ipCamId = discoveredCameraInfoList.get(0).camera_id;
                    boolean ipCamHttps = discoveredCameraInfoList.get(0).https;
                    IPCamMgr.add_camera(ipCamAlias, ipCamId, ipCamUser, ipCamPwd, ipCamHttps);
                    connectFlag = false;
                }else if(camList.size()>0){//大于0
                    connectFlag =false;
                }else if(end - start >3*1000){//超时3秒
                    connectFlag =false;
                }
            }
        }
        System.out.println("camList size:"+camList.size());
        if(camList.size()>0){
            connectFlag = true;
            new Thread(connectCamera).start();
        }else{
            IPCamMgr.rediscover_cameras();
            Toast.makeText(ClientActivity.this, "请检查抄表杆！", Toast.LENGTH_SHORT).show();
        }
    }

    private BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("android.intent.action.SCREEN_OFF")) {
                IPCamMgr.need_restart();
                if (ipCam.status() == IPCam.CONN_STATUS.CONNECTED){
                    clickFlag = false;
                }
            }
        }
    };

    Runnable connectCamera = new Runnable() {
        @Override
        public void run() {
            IPCam cam = new ArrayList<>(camList.values()).get(0);
            while (connectFlag){
                if(cam.status() == IPCam.CONN_STATUS.IDLE){
                    connectFlag = false;
                    cam.start_connect(true, 3);
                } else if(cam.status() == IPCam.CONN_STATUS.CONNECTED){
                    connectFlag = false;
                    //进入视频播放界面
                    ipCam = IPCamMgr.get_camera(cam.camera_id());
                    if (ipCam == null){
                        Toast.makeText(ClientActivity.this, "请检查抄表杆相机！", Toast.LENGTH_SHORT).show();
                    }else {
                        ipCam.set_video_view(ipCamVideoView);
                        Message msg = new Message();
                        msg.what = 0;
                        handler.sendMessage(msg);
                    }
                }
            }
        }
    };

}